/**
 * Project Name:UserController
 * File Name:UserController.java
 * Package Name:com.bwda.dsrs.systemservice.controller;
 * Date:2019年4月28日
 * Copyright (c) 2019, 江苏保旺达软件有限公司 All Rights Reserved.
 */
package com.bwda.dsrs.systemservice.controller;

import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.AesEncryptPaddingUtil;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.base.util.DateUtil;
import com.bwda.dsrs.systemservice.annotations.NeedRole;
import com.bwda.dsrs.systemservice.aspect.LogTypeEnum;
import com.bwda.dsrs.systemservice.aspect.Loggable;
import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.user.UserCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.org.OrgCreateForm;
import com.bwda.dsrs.systemservice.domain.form.org.OrgQueryForm;
import com.bwda.dsrs.systemservice.domain.form.user.*;
import com.bwda.dsrs.systemservice.domain.po.pwdrule.PwdRulePo;
import com.bwda.dsrs.systemservice.domain.po.role.RolePo;
import com.bwda.dsrs.systemservice.domain.po.role.UserByRolePo;
import com.bwda.dsrs.systemservice.domain.po.user.UserPo;
import com.bwda.dsrs.systemservice.domain.po.userinformation.UserInformationPo;
import com.bwda.dsrs.systemservice.domain.po.userlevel.UserLevelPo;
import com.bwda.dsrs.systemservice.domain.po.usersecurity.UserSecurityPo;
import com.bwda.dsrs.systemservice.domain.vo.user.UserLoginVo;
import com.bwda.dsrs.systemservice.domain.vo.user.UserVo;
import com.bwda.dsrs.systemservice.service.*;
import com.bwda.dsrs.systemservice.util.EncriptUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户菜单管理类
 *
 * @author youzhen
 * @date 2019年4月28日
 */
@RestController
@RequestMapping("/s/user")
@Api(value = "/s/user", tags = "用户表")
public class UserController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DatadictService datadictService;

    @Autowired
    private UserLevelService userLevelService;

    @Autowired
    private UserInformationService userInformationService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private LoginRuleService loginRuleService;

    @Value("${aes_key}")
    private String aesKey;
    @Autowired
    private UserSecurityService userSecurityService;

    @ApiOperation(value = "查询用户表", notes = "查询用户表", httpMethod = "GET")
    @Loggable(descp = "查询用户表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<UserPo> query(@ApiParam(value = "用户ID", required = true) @RequestParam Long userId) throws SystemServiceException {
        UserPo po = userService.queryWithValid(userId);
        return getSuccessResult(po);
    }

    @ApiOperation(value = "查询用户详情", notes = "查询用户详情", httpMethod = "GET")
    @Loggable(descp = "查询用户详情", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryDetails", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<UserQueryForm> queryDetails(@ApiParam(value = "用户ID", required = true) @RequestParam String userCode) throws SystemServiceException {
        UserQueryForm po = userService.queryDetails(userCode);
        return getSuccessResult(po);
    }

    @ApiOperation(value = "查询用户表数量", notes = "查询用户表数量", httpMethod = "GET")
    @Loggable(descp = "查询用户表数量", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@ModelAttribute @Valid UserQueryForm form) throws SystemServiceException {
        UserCondition condition = this.getConditionByQueryForm(form);
        int count = userService.queryCount(condition);
        return getSuccessResult(count);
    }

    @ApiOperation(value = "查询用户表列表", notes = "查询用户表列表", httpMethod = "GET")
    @Loggable(descp = "查询用户表列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<UserVo>> queryList(@ModelAttribute @Valid UserQueryForm form) throws SystemServiceException {
        UserCondition condition = this.getConditionByQueryForm(form);
        List<UserPo> poList = userService.queryList(condition);
        List<UserVo> voList = CopyUtil.transfer(poList, UserVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    @ApiOperation(value = "查询用户表列表(带分页)", notes = "查询用户表列表(带分页)", httpMethod = "POST")
    @Loggable(descp = "查询用户表列表(带分页)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<UserPo>> queryPageList(@ModelAttribute @Valid UserQueryForm form) throws SystemServiceException {
        UserCondition condition = this.getConditionByQueryForm(form);
        List<UserPo> poList = new ArrayList<>();
        if (form.getOrgId()!=null){
            OrgCreateForm orgCreateForm = orgService.queryByIdOrg(form.getOrgId());
            String parentIds = orgCreateForm.getParentIds()+","+form.getOrgId();
            condition.setParentIds(parentIds);
        }
        int count = userService.queryCount(condition);
        if (count > 0) {
            poList = userService.queryList(condition);
        }
        return getSuccessResult(getPageResponse(form, count, poList));
    }

    @ApiOperation(value = "查询用户表列表(带分页)接口", notes = "查询用户表列表(带分页)接口", httpMethod = "POST")
    @Loggable(descp = "查询用户表列表(带分页)接口", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<UserPo>> queryUserPageList(@RequestBody UserQueryForm form) throws SystemServiceException {
        UserCondition condition = this.getConditionByQueryForm(form);
        List<UserPo> poList = new ArrayList<>();
        int count = userService.queryCount(condition);
        if (count > 0) {
            poList = userService.queryList(condition);
        }
        return getSuccessResult(getPageResponse(form, count, poList));
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "新增用户表", notes = "新增用户表", httpMethod = "POST")
    @Loggable(descp = "新增用户表", type = LogTypeEnum.CREATE, include = "")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<UserVo> add(@ModelAttribute @Valid UserCreateForm form, HttpServletRequest request) throws SystemServiceException {
        //用户表
        if (form.getUserCode() != null) {
            int count = userService.checkUserCode(form.getUserCode());
            if (count > 0) {
                return getFailResult("登录名已存在");
            }
        }
        if (form.getMobilePhone() != null && !"".equals(form.getMobilePhone())) {
            int countTel = userService.checkPhoneUnique(form.getMobilePhone(), Constants.TYPE_ID, form.getUserCode());
            if (countTel > 0) {
                return getFailResult("手机号已存在");
            }
        }
        if (form.getEmail() != null && !"".equals(form.getEmail())) {
            int countEmail = userService.checkEmailUnique(form.getEmail(), Constants.TYPE_ID, form.getUserCode());
            if (countEmail > 0) {
                return getFailResult("邮箱已存在");
            }
        }
        if (form.getIdentityCard() != null && !"".equals(form.getIdentityCard())) {
            int countId = userService.checkIdnumberUnique(form.getIdentityCard(), Constants.TYPE_ID, form.getUserCode());
            if (countId > 0) {
                return getFailResult("身份证号已存在");
            }
        }

        UserPo po = CopyUtil.transfer(form, UserPo.class);
        String creatUserCode = getUserCodeVal();
        if (Constants.TOKEN_ERROR.equals(creatUserCode)) {
            return getFailResult("token无效");
        }
        po.setUserSource(Constants.ONE_INT);
        po.setCreateUserCode(creatUserCode);
        userService.insertUser(po);
        //用户详情表
        UserInformationPo inpo = CopyUtil.transfer(form, UserInformationPo.class);
        userInformationService.insert(inpo);
        //用户角色绑定
        UserRoleForm userRoleForm = new UserRoleForm();
        String[] roleId = form.getUserRole().split(",");
        for (int i = 0; i < roleId.length; i++) {
            userRoleForm.setRoleId(Integer.parseInt(roleId[i]));
            userRoleForm.setUserCode(po.getUserCode());
            userService.insertRole(userRoleForm);
        }
        UserVo vo = CopyUtil.transfer(po, UserVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "检查用户Code", notes = "检查用户Code", httpMethod = "POST")
    @Loggable(descp = "检查用户Code", type = LogTypeEnum.DELETE, include = "")
    @RequestMapping(value = "/checkUserCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity checkUserCode(@ApiParam(value = "用户Code", required = true) @RequestParam String userCode) throws SystemServiceException {
        int count = userService.checkUserCode(userCode);
        boolean code = true;
        if (count > 0) {
            code = false;
        }
        return getSuccessResult(code);
    }


    @ApiOperation(value = "修改用户表", notes = "修改用户表", httpMethod = "POST")
    @Loggable(descp = "修改用户表", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity update(@ModelAttribute @Valid UserCreateForm form) throws SystemServiceException {
        UserPo po = CopyUtil.transfer(form, UserPo.class);
        if(StringUtils.isNotEmpty(form.getMobilePhone())){
            int countTel = userService.checkPhoneUnique(form.getMobilePhone(), Constants.QUIT_STATUS, form.getUserCode());
            if (countTel > 0) {
                return getFailResult("手机号已存在");
            }
        }

        if(StringUtils.isNotEmpty(form.getEmail())){
            int countEmail = userService.checkEmailUnique(form.getEmail(), Constants.QUIT_STATUS, form.getUserCode());
            if (countEmail > 0) {
                return getFailResult("邮箱已存在");
            }
        }
        if(StringUtils.isNotEmpty(form.getIdentityCard())){
            int countId = userService.checkIdnumberUnique(form.getIdentityCard(), Constants.QUIT_STATUS, form.getUserCode());
            if (countId > 0) {
                return getFailResult("身份证号已存在");
            }
        }

        userService.update(po);
        UserInformationPo inpo = CopyUtil.transfer(form, UserInformationPo.class);
        userInformationService.update(inpo);
        UserRoleForm userRoleForm = new UserRoleForm();
        String[] roleId = form.getUserRole().split(",");
        userService.deleteRole(form.getUserCode());
        for (int i = 0; i < roleId.length; i++) {
            userRoleForm.setRoleId(Integer.parseInt(roleId[i]));
            userRoleForm.setUserCode(form.getUserCode());
            userService.insertRole(userRoleForm);
        }
        return getSuccessResult();
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "删除用户表", notes = "删除用户表", httpMethod = "POST")
    @Loggable(descp = "删除用户表", type = LogTypeEnum.DELETE, include = "")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity delete(@ApiParam(value = "用户ID", required = true) @RequestParam String ids) throws SystemServiceException {
        userService.deleteUserByIds(ids);
        return getSuccessResult();
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "用户重置密码", notes = "用户重置密码", httpMethod = "POST")
    @Loggable(descp = "用户重置密码", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/resetPassword", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity resetPassword(@ApiParam(value = "用户ID", required = true) @RequestParam String ids) throws SystemServiceException {

        String password = datadictService.getDataDictValByCode("initpassword");
        userService.resetPassword(ids, password);
        return getSuccessResult();
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "修改用户状态", notes = "修改用户状态", httpMethod = "POST")
    @Loggable(descp = "修改用户状态", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/updateState", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity updateState(@RequestParam String userIds, @RequestParam long state) throws SystemServiceException {

        boolean result = userService.updateState(userIds, state);
        if (!result) {
            return getFailResult("离职的用户不可操作状态");
        }
        return getSuccessResult();
    }

    @ApiOperation(value = "用户修改密码", notes = "用户修改密码", httpMethod = "POST")
    @Loggable(descp = "用户修改密码", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/updatePassword", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity updatePassword(@RequestParam String oldPwd, String password, String confirmPwd, HttpServletRequest request) throws SystemServiceException {
        String userCode = getUserCode();
        UserPo userPo = userService.queryUserByUserCode(userCode);
        if (userPo == null) {
            logger.error("操作用户不存在");
            return getFailResult("操作失败");
        }
        try {
            //解密前端AES加密的内容
            oldPwd = AesEncryptPaddingUtil.decrypt(oldPwd, aesKey);
            password = AesEncryptPaddingUtil.decrypt(password, aesKey);
            confirmPwd = AesEncryptPaddingUtil.decrypt(confirmPwd, aesKey);
        } catch (Exception e) {
            logger.error("初始密码解密异常：" + e.getMessage());
        }
        //是否开启外部密码认证
        String outerPwdAuth = datadictService.getDataDictValByCode("root.outer.authway");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //校验初始密码正确性
        this.checkInitPwdValidity(oldPwd, userPo);
        //输入初始密码与认证密码不能相同
        if (StringUtils.equals(oldPwd, confirmPwd)) {
            return getFailResult("用户初始密码和新密码不能相同！");
        }
        //密码不能为空
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPwd)) {
            return getFailResult("密码为空");
        }
        //输入密码与认证密码需要一致
        if (!StringUtils.equals(password, confirmPwd)) {
            return getFailResult("用户新密码和确认密码不一致！");
        }
        //校验密码规则
        userService.checkPwdFormat(userCode, confirmPwd);
        //服务默认加密方式（未开启用户同步密码认证或者通过内部创建的用户）
        if (Constants.ZERO_STR.equals(outerPwdAuth) || Constants.ONE_INT.equals(userPo.getUserSource())) {
            //旧密码设置为历史密码
            if (!StringUtils.isEmpty(userPo.getHisPwdOne())) {
                //有旧密码1，1移到2
                userPo.setHisPwdOtwo(userPo.getHisPwdOne());
            }
            userPo.setHisPwdOne(encoder.encode(oldPwd));
            //BCrypt强哈希方法进行加密
            userPo.setPassword(encoder.encode(confirmPwd.trim()));
        } else {
            //旧密码设置为历史密码
            if (!StringUtils.isEmpty(userPo.getHisPwdOne())) {
                //有旧密码1，1移到2
                userPo.setHisPwdOtwo(userPo.getHisPwdOne());
            }
            //4a用户登录密码md5加密方式 0：密码直接md5,1：用户名+密码+密码随机数md5
            String loginMd5 = datadictService.getDataDictValByCode("root.loginMd5");
            String fullPwdMd5 = "";
            String oldFullPwdMd5 = "";
            String fullPwd = "";
            String oldFullPwd = "";
            if (Constants.ZERO_STR.equals(loginMd5)) {
                fullPwd = confirmPwd;
                oldFullPwd = oldPwd;
            } else {
                fullPwd = userCode + confirmPwd + userPo.getSalt();
                oldFullPwd = userCode + oldPwd + userPo.getSalt();
            }
            fullPwdMd5 = EncriptUtil.encodePwd(fullPwd);
            oldFullPwdMd5 = EncriptUtil.encodePwd(oldFullPwd);
            userPo.setHisPwdOne(oldFullPwdMd5);
            userPo.setPassword(fullPwdMd5);
        }
        //更新用户密码
        userService.updatePassword(userPo);

        PwdRulePo pwdRulePo = loginRuleService.queryWithValid(Constants.ONE_INT);
        //更新个人安全策略
        UserSecurityPo userSecurityPo = userSecurityService.querySecurityByUserCode(userCode);
        userSecurityPo.setPwdLastUpdateTime(new Date());
        userSecurityPo.setPwdUpdateTime(DateUtil.getAssignDate(pwdRulePo.getValidDays().intValue()));
        userSecurityService.update(userSecurityPo);

        return getSuccessResult("密码更新成功");
    }

    @ApiOperation(value = "用户修改密码", notes = "用户修改密码", httpMethod = "POST")
    private void checkInitPwdValidity(String oldPwd, UserPo userPo) throws SystemServiceException {
        //是否开启外部密码认证（未开启用户同步密码认证或者通过内部创建的用户）
        String outerPwdAuth = datadictService.getDataDictValByCode("root.outer.authway");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //服务默认加密方式
        if (Constants.ZERO_STR.equals(outerPwdAuth) || Constants.ONE_INT.equals(userPo.getUserSource())) {
            if (!encoder.matches(oldPwd, userPo.getPassword())) {
                throw new SystemServiceException("初始密码不正确！");
            }
        } else {
            //4a用户登录密码md5加密方式 0：密码直接md5,1：用户名+密码+密码随机数md5
            String loginMd5 = datadictService.getDataDictValByCode("root.loginMd5");
            String fullPwdMd5 = "";
            String fullPwd = "";
            if (Constants.ZERO_STR.equals(loginMd5)) {
                fullPwd = oldPwd;
            } else {
                fullPwd = userPo.getUserCode() + oldPwd + userPo.getSalt();
            }
            fullPwdMd5 = EncriptUtil.encodePwd(fullPwd);
            if (!userPo.getPassword().equals(fullPwdMd5)) {
                throw new SystemServiceException("初始密码不正确！");
            }
        }
    }

    @ApiOperation(value = " 查询当前用户等级下的用户", notes = " 查询当前用户等级下的用户", httpMethod = "POST")
    @Loggable(descp = " 查询当前用户等级下的用户", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/queryUserByIncludeLevel", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<List<UserByRolePo>> queryUserByIncludeLevel(@RequestBody UserCondition form) throws SystemServiceException {
        List<UserByRolePo> listUser = userService.queryUserByIncludeLevel(form);
        return getSuccessResult(listUser);
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "Excel导入", notes = "Excel导入", httpMethod = "POST")
    @Loggable(descp = "Excel导入", type = LogTypeEnum.IMPORT, include = "")
    @RequestMapping(value = "/importData", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity importData(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "orgId") int orgId, HttpServletRequest request) throws Exception {
        String creatUserCode = getUserCodeVal();
        if (Constants.TOKEN_ERROR.equals(creatUserCode)) {
            return getFailResult("token无效");
        }

        List<UserExcelImport> userList = new ArrayList<>();
        String message = userService.importUser(userList, creatUserCode, orgId);
        return getSuccessResult(message);
    }

    @ApiOperation(value = "用户职级", notes = "用户职级", httpMethod = "POST")
    @Loggable(descp = "用户职级", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryLevel", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity queryLevel() throws Exception {
        List<UserLevelPo> list = userLevelService.queryUserLevelByLevelType("RANK");
        return getSuccessResult(list);
    }

    @ApiOperation(value = "查询是否是特权用户", notes = "查询是否是特权用户", httpMethod = "POST")
    @Loggable(descp = "查询是否是特权用户", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryIsTq", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity queryIsTq(@RequestParam String userCode) throws Exception {
        boolean flag = userService.checkUserIsTq(userCode);
        return getSuccessResult(flag);
    }

    @ApiOperation(value = "用户详情查询", notes = "用户查询表", httpMethod = "POST")
    @Loggable(descp = "用户详情查询", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserByUserCode")
    public ResponseEntity<UserVo> queryUserByUserCode(@RequestParam String userCode) throws SystemServiceException {
        UserPo userPo = userService.queryUserByUserCode(userCode);
        UserVo vo = CopyUtil.transfer(userPo, UserVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "用户详情查询", notes = "用户查询表", httpMethod = "POST")
    @Loggable(descp = "用户详情查询", type = LogTypeEnum.QUERY, include = "")

    @RequestMapping(value = "/api/queryUserByUserCode", method = {RequestMethod.GET, RequestMethod.POST})
    public UserVo apiQueryUserByUserCode(@RequestParam(value = "userCode") String userCode) throws SystemServiceException {
        UserPo userPo = userService.queryUserByUserCode(userCode);
        UserVo vo = CopyUtil.transfer(userPo, UserVo.class);
        return vo;
    }


    @ApiOperation(value = "用户角色", notes = "用户角色", httpMethod = "POST")
    @Loggable(descp = "用户角色", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryRole", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity queryRole() throws Exception {
        List<RolePo> list = roleService.queryRoleList();
        return getSuccessResult(list);
    }

    @ApiOperation(value = "根据用户Code查询角色", notes = "根据用户Code查询角色", httpMethod = "POST")
    @Loggable(descp = "根据用户Code查询角色", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryRoleByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity queryRoleByCode(@RequestParam("userCode") String userCode) throws Exception {
        List<RolePo> list = roleService.queryRoleByCode(userCode);
        return getSuccessResult(list);
    }

    @ApiOperation(value = "初始密码", notes = "初始密码", httpMethod = "POST")
    @Loggable(descp = "初始密码", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryPwd", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity queryPwd() throws Exception {
        String password = datadictService.getDataDictValByCode("initpassword");
        return getSuccessResult(password);
    }
    @NeedRole("sysadminrole")
    @ApiOperation(value = "人员组织迁移", notes = "人员组织迁移", httpMethod = "POST")
    @Loggable(descp = "人员组织迁移", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/transferUserOrg", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> transferUserOrg(@RequestParam String userIds, Integer orgId) throws Exception {
        boolean result = userService.transferUserOrg(userIds, orgId);
        if (result) {
            return getSuccessResult();
        } else {
            return getFailResult("选中用户已在该组织下");
        }
    }

    @ApiOperation(value = "查询批量组织", notes = "查询批量组织", httpMethod = "GET")
    @Loggable(descp = "查询批量组织", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public List<UserForm> queryUserByCode(@ApiParam(value = "userCodes", required = true) @RequestParam("userCodes") String userCodes) throws SystemServiceException {
        List<UserForm> poList = userService.queryUserByCode(userCodes);
        return poList;
    }


    @ApiOperation(value = "根据usercode列表查询用户信息列表", notes = "根据usercode列表查询用户信息列表", httpMethod = "GET")
    @Loggable(descp = "根据usercode列表查询用户信息列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserByUserCodeList", method = {RequestMethod.GET, RequestMethod.POST})
    public List<UserForm> queryUserByUserCodeList(@ApiParam(value = "userCodes", required = true) @RequestParam("userCodes") List<String> userCodes) throws SystemServiceException {
        String[] codes = userCodes.toArray(new String[]{});
        List<UserForm> poList = userService.queryUserByUserCodeList(codes);
        return poList;
    }

    @ApiOperation(value = "查询用户单表数据", notes = "查询用户单表数据", httpMethod = "GET")
    @Loggable(descp = "查询用户单表数据", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUser", method = {RequestMethod.GET, RequestMethod.POST})
    public List<UserForm> queryUser(@ModelAttribute @Valid UserForm userForm) throws SystemServiceException {
        List<UserForm> poList = userService.queryUser(userForm);
        return poList;
    }

    @ApiOperation(value = "查询组织下的人包含子组织的人", notes = "查询组织下的人包含子组织的人", httpMethod = "POST")
    @Loggable(descp = "查询组织下的人包含子组织的人", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryByOrgIdUser", method = {RequestMethod.GET, RequestMethod.POST})
    public List<UserForm> queryByOrgIdUser(@ApiParam(value = "用户ID", required = true) @RequestParam Integer orgId) throws SystemServiceException {
        List<UserForm> userList = userService.queryByOrgIdUser(orgId);
        return userList;
    }

    @ApiOperation(value = "查询组织管理员", notes = "查询组织管理员", httpMethod = "POST")
    @Loggable(descp = "查询组织管理员", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryOrgAdminCode", method = {RequestMethod.GET, RequestMethod.POST})
    public String queryOrgAdminCode(@ApiParam(value = "用户ID", required = true) @RequestParam("userCode") String userCode) throws SystemServiceException {
        String adminCode = userService.queryOrgAdminCode(userCode);
        return adminCode;
    }

    @ApiOperation(value = "查询组织下的人", notes = "查询组织下的人", httpMethod = "POST")
    @Loggable(descp = "查询组织下的人", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryUserListByOrgId", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<List<UserForm>> queryUserListByOrgId(@ApiParam(value = "用户ID", required = true) @RequestParam Integer orgId) throws SystemServiceException {
        List<UserForm> userList = userService.queryByOrgIdUser(orgId);
        return getSuccessResult(userList);
    }

    @ApiOperation(value = "查询单个组织下的人", notes = "查询单个组织下的人", httpMethod = "POST")
    @Loggable(descp = "查询单个组织下的人", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryUserByOrgId", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<UserPo>> queryUserByOrgId(@RequestBody @Valid OrgQueryForm form) throws SystemServiceException {
        UserCondition condition = new UserCondition();
        condition.setOrgId(form.getId());
        condition.setPageNum(form.getPageNum());
        condition.setPageSize(form.getPageSize());
        condition.setUserCode(form.getUserCode());
        condition.setUserName(form.getUserName());
        List<UserPo> userList = new ArrayList<>();
        int count = userService.queryUserByOrgIdCount(condition);
        if (count > 0) {
            userList = userService.queryUserByOrgId(condition);
        }
        return getSuccessResult(getPageResponse(form, count, userList));
    }

    @ApiOperation(value = "查询单个组织下的人", notes = "查询单个组织下的人", httpMethod = "POST")
    @Loggable(descp = "查询单个组织下的人", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryUserForm", method = {RequestMethod.GET, RequestMethod.POST})
    public List<UserPo> queryUserForm(@RequestBody @Valid FileSpaceSettingQueryForm form) throws SystemServiceException {
        List<UserPo> userList = userService.queryUserForm(form);
        return userList;
    }

    @ApiOperation(value = "查询单个组织下的人", notes = "查询单个组织下的人", httpMethod = "POST")
    @Loggable(descp = "查询单个组织下的人", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/queryUserFormCount", method = {RequestMethod.GET, RequestMethod.POST})
    public int queryUserFormCount(@RequestBody @Valid FileSpaceSettingQueryForm form) throws SystemServiceException {
        int count = userService.queryUserFormCount(form);
        return count;
    }

    @ApiOperation(value = "是否更改密码", notes = "是否更改密码", httpMethod = "POST")
    @Loggable(descp = "是否更改密码", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/checkPwd", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> checkPwd(@RequestParam(value = "userCode") String userCode) throws SystemServiceException {
        UserLoginVo userLoginVo = userService.checkPwd(userCode);
        if (!"".equals(userLoginVo.getHisPwdOne())) {
            return getSuccessResult();
        } else {
            return getFailResult("初始密码未修改");
        }
    }


    /**
     * UserQueryForm转换为UserCondition
     * 如果不修改密码，7天后锁定账号
     *
     * @param form
     * @return
     */
    private UserCondition getConditionByQueryForm(UserQueryForm form) {
        UserCondition condition = CopyUtil.transfer(form, UserCondition.class);
        return condition;
    }

    private String getUserCodeVal() throws SystemServiceException {
        String userCode = getUserCode();
        if (StringUtils.isBlank(userCode)) {
            logger.error("获取用户信息异常");
            return null;
        }
        return userCode;
    }


}